package com.kitty.game.hunqiao;

import com.kitty.common.utils.SpringUtils;
import com.kitty.game.bag.message.RespIconCartoon;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.EquipField;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.hunqiao.enums.FieldsEnum;
import com.kitty.game.hunqiao.enums.HunQiaoColorEnum;
import com.kitty.game.npc.NpcDataPool;
import com.kitty.game.role.model.Role;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.utils.JsonUtils;
import com.kitty.mina.codec.xf.StanUtils;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
//后加
import com.kitty.game.hunqiao.message.HunQiaoCangKu;
import com.kitty.game.hunqiao.message.HunQiaoRespEquipInfo;
import com.kitty.game.hunqiao.message.HunQiaoTenBack;
import com.kitty.game.hunqiao.message.RequestOpenHunQiao;
import com.kitty.game.hunqiao.message.RespEnterCustomBack;
import com.kitty.game.hunqiao.model.HunQiaoData;
import com.kitty.game.hunqiao.model.HunQiaoField;
import com.kitty.game.hunqiao.model.HunQiaoStoreEquipInfo;
import com.kitty.game.hunqiao.model.HunQiaoToSave;
import com.kitty.game.hunqiao.model.HunQiaoZhuRuEquipInfo;


@Service
@Slf4j
public class HunQiaoService {
    public static short startPosition = 5401;
    public static short endPosition = 5499;
    public static int cangKuSize = 99;

    @Autowired
    private Dao dao;


    static {
        //初始化npc处理
        // npc对话：地藏王-了解地宫
//        NpcDataPool.npcButtonHandlers.put("introduce_digong", (npcButtonParam -> {
//            TalkSet talkSet =   SpringUtils.getBean(TalkService.class).getTalkSet(1297,npcButtonParam.getRole());
//            SpringUtils.getBean(TalkService.class).popFirstTalk(npcButtonParam.getRole(), talkSet);
//        }));
        // npc对话：冥海引魂 打开抽取魂窍界面
        NpcDataPool.npcButtonHandlers.put("冥海引魂", (npcButtonParam -> {
            int level = SpringUtils.getBean(HunQiaoService.class).hunQiaoToSave(npcButtonParam.getRole()).getLevel();
            RequestOpenHunQiao requestOpenHunQiao = new RequestOpenHunQiao();
            requestOpenHunQiao.setData(StanUtils.hexToByteArray("010"+level+"00"));
            MessagePusher.pushMessage(npcButtonParam.getRole(), requestOpenHunQiao);
        }));
    }
    public void addHunQiao(Role role, List<HunQiaoField> hunQiFields ){
        //仓库，组装这个参数，回包
        HunQiaoCangKu hunQiaoCangKu = new HunQiaoCangKu();
        //仓库类别
        hunQiaoCangKu.setStr("tyzq_store");
        HunQiaoToSave hunQiaoToSave = hunQiaoToSave(role.getRoleId());
        List<HunQiaoStoreEquipInfo> list = new ArrayList<>();
        if(!hasPosition(role,1,hunQiaoToSave)){//这个前端限死了，但是后端还是加上吧
            MessagePusher.pushMessage(role,new RespMsg("仓库空间不足"));
            return;
        }
        //魂窍当个装备来看
        HunQiaoStoreEquipInfo hunQiaoStoreEquipInfo = new HunQiaoStoreEquipInfo();
        //位置相同会覆盖
        short pos = newPosition(hunQiaoToSave);
        hunQiaoStoreEquipInfo.setPos(pos);
        List<EquipField> equipFields = new ArrayList<>();
        //根据颜色组装equipField ，加入equipFields 列表
        equipFields.add(genEquipField(HunQiaoColorEnum.GOLD,hunQiaoToSave));
        hunQiaoStoreEquipInfo.setEquipFields(equipFields,hunQiFields);
        //组合参数，发包
        list.add(hunQiaoStoreEquipInfo);
        hunQiaoCangKu.setList(list);
        //拼好参数，入库
        List<HunQiaoStoreEquipInfo> hunQiaoStoreEquipInfos = hunQiaoCangKu.getList();
        hunQiaoToSave.getCangKus().addAll(hunQiaoStoreEquipInfos);
        update(role.getRoleId(),hunQiaoToSave);

        hunQiaoCangKu.addMore();
        MessagePusher.pushMessage(role,hunQiaoCangKu );

        MessagePusher.pushMessage(role,new RespMsg("恭喜你，获得一个太阴之气"));
    }
    /**
     * 随机生成个
     * @param role 角色
     */
    public void chouYiCi(Role role, RoleEquip roleEquip){
        //仓库，组装这个参数，回包
        HunQiaoCangKu hunQiaoCangKu = new HunQiaoCangKu();
        HunQiaoToSave hunQiaoToSave = hunQiaoToSave(role.getRoleId());
        //仓库类别
        hunQiaoCangKu.setStr("tyzq_store");
        List<HunQiaoStoreEquipInfo> list = new ArrayList<>();
        if(!hasPosition(role,1,hunQiaoToSave)){//这个前端限死了，但是后端还是加上吧
            MessagePusher.pushMessage(role,new RespMsg("仓库空间不足"));
            return;
        }
        int delCountSuc = SpringUtils.getEquipService().delEquipNum(role, roleEquip, 1);
        /**没有使用成功返回*/
        if (delCountSuc <= 0) {
            return ;
        }
        try{
            //魂窍当个装备来看
            HunQiaoStoreEquipInfo hunQiaoStoreEquipInfo = new HunQiaoStoreEquipInfo();
            //位置相同会覆盖
            short pos = newPosition(hunQiaoToSave);
            hunQiaoStoreEquipInfo.setPos(pos);

            List<EquipField> equipFields = new ArrayList<>();
            //当前魂窍等级，随机个颜色参数
            HunQiaoColorEnum hunQiaoColorEnum = HunQiaoColorEnum.random(hunQiaoToSave.getLevel());
            //根据颜色组装equipField ，加入equipFields 列表
            equipFields.add(genEquipField(hunQiaoColorEnum,hunQiaoToSave));
            //根据颜色属性个数，随机HunQiaoField 属性列表，设值并计算size
            hunQiaoStoreEquipInfo.setEquipFields(equipFields,randomField(hunQiaoColorEnum.getFieldNum()));
            //组合参数，发包
            list.add(hunQiaoStoreEquipInfo);
            hunQiaoCangKu.setList(list);


            //加一阶引魂阶段
            addHunQiaoLevel(hunQiaoToSave);
            //拼好参数，入库
            List<HunQiaoStoreEquipInfo> hunQiaoStoreEquipInfos = hunQiaoCangKu.getList();
            hunQiaoToSave.getCangKus().addAll(hunQiaoStoreEquipInfos);
            update(role.getRoleId(),hunQiaoToSave);

            hunQiaoCangKu.addMore();
            MessagePusher.pushMessage(role,hunQiaoCangKu );

            //更新引魂阶段
            RequestOpenHunQiao respEnterCustom2 = new RequestOpenHunQiao();
            respEnterCustom2.setData(StanUtils.hexToByteArray("000"+hunQiaoToSave.getLevel()+"00"));
            MessagePusher.pushMessage(role, respEnterCustom2);
            //提示
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("你消耗了#R1道#n冥海霞光进行引魂获得#R"+hunQiaoColorEnum.getColor()+"#n品质的太阴之气"));
            // 播放动画
            RespEnterCustomBack respEnterCustomBack = new RespEnterCustomBack();
            respEnterCustomBack.setName("冥海霞光");
            respEnterCustomBack.setPos(pos);//中东西的位置
            MessagePusher.pushMessage(role, respEnterCustomBack);
        }catch (Exception e){

        }

    }

    public void ten(Role role){
        //仓库，组装这个参数，回包
        HunQiaoCangKu hunQiaoCangKu = new HunQiaoCangKu();
        HunQiaoToSave hunQiaoToSave =  hunQiaoToSave(role.getRoleId());

        //仓库类别
        hunQiaoCangKu.setStr("tyzq_store");
        List<HunQiaoStoreEquipInfo> list = new ArrayList<>();
        if(!hasPosition(role,10,hunQiaoToSave)){//这个前端限死了，但是后端还是加上吧
            MessagePusher.pushMessage(role,new RespMsg("仓库空间不足"));
            return;
        }

        int restNum = SpringUtils.getEquipService().getCount("冥海霞光",true,role);
        if(restNum<10){
            MessagePusher.pushMessage(role,new RespMsg("冥海霞光数量不足"));
            return;
        }
        //扣物品，不知道为什么返回数没用。
        SpringUtils.getEquipService().delRoloEquip("冥海霞光",10, true, role);

        int[] positions = new int[10];

        for(int i = 0;i<10;i++){
            HunQiaoStoreEquipInfo hunQiaoStoreEquipInfo = new HunQiaoStoreEquipInfo();
            //位置相同会覆盖
            short pos = newPosition(hunQiaoToSave);
            positions[i]=pos;
            hunQiaoStoreEquipInfo.setPos(pos);

            List<EquipField> equipFields = new ArrayList<>();
            //当前魂窍等级，随机个颜色参数
            HunQiaoColorEnum hunQiaoColorEnum = HunQiaoColorEnum.random(hunQiaoToSave.getLevel());
            //根据颜色组装equipField ，加入equipFields 列表
            equipFields.add(genEquipField(hunQiaoColorEnum,hunQiaoToSave));
            //根据颜色属性个数，随机HunQiaoField 属性列表，设值并计算size
            hunQiaoStoreEquipInfo.setEquipFields(equipFields,randomField(hunQiaoColorEnum.getFieldNum()));
            //组合参数，发包
            list.add(hunQiaoStoreEquipInfo);

            //加一阶引魂阶段
            addHunQiaoLevel(hunQiaoToSave);

            //加进去，否则下次循环同一个position
            hunQiaoToSave.getCangKus().add(hunQiaoStoreEquipInfo);
        }
        update(role.getRoleId(),hunQiaoToSave);

        hunQiaoCangKu.setList(list);
        hunQiaoCangKu.addMore();
        MessagePusher.pushMessage(role, hunQiaoCangKu);

        HunQiaoTenBack hunQiaoTenBack = new HunQiaoTenBack();
        hunQiaoTenBack.setPositions(positions);
        MessagePusher.pushMessage(role,hunQiaoTenBack);
    }

    public EquipField genEquipField( HunQiaoColorEnum hunQiaoColorEnum ,HunQiaoToSave hunQiaoToSave){
        EquipField equipField = new EquipField();
        List<FiedValue> fieldValues = new ArrayList<>();
        fieldValues.add(new FiedValue((short)84,(byte)3, hunQiaoToSave.itemUnique()));//item_unique
        fieldValues.add(new FiedValue((short)209,(byte)4,hunQiaoColorEnum.getColor()));
        fieldValues.add(new FiedValue((short)40,(byte)7,hunQiaoColorEnum.getIcon()));//icon  控制弹出来的图标颜色
        equipField.setFieldValues(fieldValues);
        return equipField;
    }

    /**
     * 随机属性，
     * @param num 几条属性
     */
    public List<HunQiaoField> randomField(int num){
        List<HunQiaoField> list = new ArrayList<>();
        for(int i= 0; i< num; i++ ){
            //属性枚举，随机获得属性
            FieldsEnum fieldsEnum = FieldsEnum.random();
            //构造参数
            HunQiaoField hunQiaoField =  new HunQiaoField();
            //todo 不知道什么，不加2 还不行
            hunQiaoField.setPos((byte)(i+2));
            hunQiaoField.setId(fieldsEnum.fieldId);
            hunQiaoField.setVal(fieldsEnum.randomValue());
            list.add(hunQiaoField);
        }
        return list;
    }


    public List<HunQiaoField> getField(String shuxing1 ,int value1 ,String shuxing2  ,int value2 ,String shuxing3 ,int value3){
        List<HunQiaoField> list = new ArrayList<>();
        FieldsEnum[] fieldsEnums = FieldsEnum.values();
        for (FieldsEnum fieldsEnum1 : fieldsEnums){
            if(fieldsEnum1.name.equals(shuxing1)){
                HunQiaoField hunQiaoField =  new HunQiaoField();
                hunQiaoField.setPos((byte)(2));
                hunQiaoField.setId(fieldsEnum1.fieldId);
                if(value1 < fieldsEnum1.minValueHunQiao){
                    hunQiaoField.setVal(fieldsEnum1.minValueHunQiao) ;
                }else if(value1 > fieldsEnum1.maxValueHunQiao){
                    hunQiaoField.setVal(fieldsEnum1.maxValueHunQiao) ;
                }else {
                    hunQiaoField.setVal((short)value1);
                }
                list.add(hunQiaoField);
            }
        }

        for (FieldsEnum fieldsEnum1 : fieldsEnums){
            if(fieldsEnum1.name.equals(shuxing2)){
                HunQiaoField hunQiaoField =  new HunQiaoField();
                hunQiaoField.setPos((byte)(3));
                hunQiaoField.setId(fieldsEnum1.fieldId);
                if(value2 < fieldsEnum1.minValueHunQiao){
                    hunQiaoField.setVal(fieldsEnum1.minValueHunQiao) ;
                }else if(value2 > fieldsEnum1.maxValueHunQiao){
                    hunQiaoField.setVal(fieldsEnum1.maxValueHunQiao) ;
                }else {
                    hunQiaoField.setVal((short)value2);
                }
                list.add(hunQiaoField);
            }
        }

        for (FieldsEnum fieldsEnum1 : fieldsEnums){
            if(fieldsEnum1.name.equals(shuxing3)){
                HunQiaoField hunQiaoField =  new HunQiaoField();
                hunQiaoField.setPos((byte)(4));
                hunQiaoField.setId(fieldsEnum1.fieldId);

                if(value3 < fieldsEnum1.minValueHunQiao){
                    hunQiaoField.setVal(fieldsEnum1.minValueHunQiao) ;
                }else if(value3 > fieldsEnum1.maxValueHunQiao){
                    hunQiaoField.setVal(fieldsEnum1.maxValueHunQiao) ;
                }else {
                    hunQiaoField.setVal((short)value3);
                }


                list.add(hunQiaoField);
            }
        }


        return list ;
    }


    /**
     * 获得一个空位
     * @return 0表示满了，非0正常空位
     */
    public short newPosition(HunQiaoToSave hunQiaoToSave){
        short newPosition  = 0;
        List<HunQiaoStoreEquipInfo> hunQiaoStoreEquipInfos = hunQiaoToSave.getCangKus();
        if(hunQiaoStoreEquipInfos!=null){
            for(short i = startPosition;i<=endPosition;i++){
                boolean flag = false; // 表示 i 位置没有 太阴之气
                for (HunQiaoStoreEquipInfo hunQiaoStoreEquipInfo : hunQiaoStoreEquipInfos){
                    if(i==hunQiaoStoreEquipInfo.getPos()){
                        flag=true;
                        break;
                    }
                }
                if(!flag){
                    newPosition = i;
                    break;
                }
            }
        }else {
            newPosition = startPosition;
        }
        return newPosition;
    }
    /** 仓库是否还有位置 **/
    public boolean hasPosition(Role role,int num,HunQiaoToSave hunQiaoToSave ){
        List<HunQiaoStoreEquipInfo> hunQiaoStoreEquipInfos = hunQiaoToSave.getCangKus();
        return hunQiaoStoreEquipInfos.size()+num<=cangKuSize;
    }
    /**
     * 加一阶魂窍等级
     */
    public void addHunQiaoLevel(HunQiaoToSave hunQiaoToSave){
        int level = hunQiaoToSave.getLevel();
        if(level == 5){
            hunQiaoToSave.setLevel(1);
        }else{
            hunQiaoToSave.setLevel(level+1);
        }
    }
    /** 存库 **/
    public void update(Role role, HunQiaoToSave hunQiaoToSave){
        //保存到role上
        role.setHunqiaoJson(Json.toJson(hunQiaoToSave));
        role.save();
        log.error("角色对象上保存魂窍数据=={}=={}",role.getRoleId(),role.getName());
//        dao.update(HunQiaoData.class, Chain.make("data", JsonUtils.object2String(hunQiaoToSave)), Cnd.where("roleId","=",role.getRoleId()));
    }

    /** 存库 **/
    public void update(int roleId, HunQiaoToSave hunQiaoToSave){
        dao.update(HunQiaoData.class, Chain.make("data", JsonUtils.object2String(hunQiaoToSave)), Cnd.where("roleId","=",roleId));
    }

    public HunQiaoToSave hunQiaoToSave(Role  role){
        HunQiaoToSave hunQiaoToSave;
        if (role.getHunqiaoJson() != null){
            hunQiaoToSave = Json.fromJson(HunQiaoToSave.class,role.getHunqiaoJson());
            log.error("角色对象上获得魂窍数据=={}=={}",role.getRoleId(),role.getName());
            return hunQiaoToSave;
        }
        int roleId = role.getRoleId();
        HunQiaoData hunQiaoData = dao.fetch(HunQiaoData.class, roleId);
        if(hunQiaoData==null){
            hunQiaoToSave= new HunQiaoToSave();
        }else{
            hunQiaoToSave = JsonUtils.string2Object(hunQiaoData.getData(),HunQiaoToSave.class);
        }
        log.error("转化魂窍数据到角色对象上=={}=={}",role.getRoleId(),role.getName());
        role.setHunqiaoJson(Json.toJson(hunQiaoToSave));
        role.save();
        return hunQiaoToSave;
    }

    public HunQiaoToSave hunQiaoToSave(int roleId){
        HunQiaoData hunQiaoData = dao.fetch(HunQiaoData.class, roleId);
        HunQiaoToSave hunQiaoToSave;
        if(hunQiaoData==null){
            hunQiaoData = new HunQiaoData();
            hunQiaoToSave= new HunQiaoToSave();
            hunQiaoData.setData(JsonUtils.object2String(hunQiaoToSave));
            hunQiaoData.setRoleId(roleId);
            dao.insert(hunQiaoData);
        }else{
            hunQiaoToSave = JsonUtils.string2Object(hunQiaoData.getData(),HunQiaoToSave.class);
        }
        return hunQiaoToSave;
    }


    //打开仓库
    public void openHunQiaoStore (Role role){
        HunQiaoToSave hunQiaoToSave =  hunQiaoToSave(role);
        List<HunQiaoStoreEquipInfo> cangKus = hunQiaoToSave.getCangKus();
        HunQiaoCangKu hunQiaoCangKu = new HunQiaoCangKu();
        hunQiaoCangKu.setStr("tyzq_store");
        hunQiaoCangKu.setList(cangKus);
        hunQiaoCangKu.addMore();
        MessagePusher.pushMessage(role, hunQiaoCangKu);

        sendZhuRu(role,hunQiaoToSave);
    }
    //发送已注入魂窍显示包
    public void sendZhuRu(Role role,HunQiaoToSave hunQiaoToSave){
        List<HunQiaoStoreEquipInfo> cangKus = hunQiaoToSave.getCangKus();

        int[] hunQiao = hunQiaoToSave.getHunQiao();
        HunQiaoRespEquipInfo hunQiaoZhuRuEquipInfo = new HunQiaoRespEquipInfo();
        List<HunQiaoZhuRuEquipInfo> list = new ArrayList<>();
        for(int i=0;i<5 ;i++){
            if(hunQiao[i]!=0){
                for(HunQiaoStoreEquipInfo hunQiaoStoreEquipInfo:cangKus){
                    boolean flag = false;
                    List<EquipField> equipFields = hunQiaoStoreEquipInfo.getEquipFields();
                    for(EquipField equipField:equipFields){
                        List<FiedValue> fiedValues = equipField.getFieldValues();
                        for(FiedValue fiedValue :fiedValues){
                            if(fiedValue.getType()==84&&fiedValue.getValue().equals(hunQiao[i])){
                                flag = true;
                            }
                        }
                        if(flag){break;}
                    }
                    if(flag){
                        HunQiaoZhuRuEquipInfo equipInfo = new HunQiaoZhuRuEquipInfo();
                        equipInfo.setPos((byte)(i+21));
                        equipInfo.setEquipFields(hunQiaoStoreEquipInfo.getEquipFields(),hunQiaoStoreEquipInfo.getHunQiaoFields());
                        list.add(equipInfo);
                        break;
                    }
                }
            }
        }
        hunQiaoZhuRuEquipInfo.setList(list);
        hunQiaoZhuRuEquipInfo.addMore();
        MessagePusher.pushMessage(role,hunQiaoZhuRuEquipInfo);
    }

    public List<HunQiaoField> hunQiaoFields(HunQiaoToSave hunQiaoToSave){
        List<HunQiaoStoreEquipInfo> cangKus = hunQiaoToSave.getCangKus();
        List<HunQiaoField> hunQiaoFields = new ArrayList<>();
        int[] hunQiao = hunQiaoToSave.getHunQiao();
        for(int i : hunQiao){
                for(HunQiaoStoreEquipInfo hunQiaoStoreEquipInfo:cangKus){
                    boolean flag = false;
                    List<EquipField> equipFields = hunQiaoStoreEquipInfo.getEquipFields();
                    for(EquipField equipField:equipFields){
                        List<FiedValue> fiedValues = equipField.getFieldValues();
                        for(FiedValue fiedValue :fiedValues){
                            if(fiedValue.getType()==84&&fiedValue.getValue().equals(i)){
                                flag = true;
                            }
                        }
                        if(flag){
                            break;
                        }
                    }
                    if(flag){
                        hunQiaoFields.addAll( hunQiaoStoreEquipInfo.getHunQiaoFields());
                        break;
                    }
                }
            }
        return hunQiaoFields;
    }
}
